// pages/addinfo/addinfo.js
const request=require('../../util/request.js')
const instruct = require('../../util/tspl')
import bleDisNetwork from '../../util/bleDisNetwork'
Page({

  /**
   * 页面的初始数据
   */
  data: {
   
    list:[],
    page: 1,//页码
    limit: 5,//每页数量
    type:0,//可不传参数
    keyword:"",//可不传参数
    add_time:"",//可不传参数
    p_no:"",//项目号
    count: 0,
    projectbody:[],//项目主体信息
    datastatus:2,//查看 2全部/1以完善/0未完成 
    datafind:"",//搜索关键字
    date:"",
    mindate:Math.round((new Date() - 365*86400*1000)),
    findtime:"",//时间范围查找
    __returnParams:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      __returnParams:false,

    })
    this.data.p_no = options.p_no
    this.data.page = 1
    this.getList()

  },

  onReachBottom() {
    if(this.data.flag){
      this.setData({
        flag:false
      })
      this.getList(); // 疯狂的请求的方法
    }
  },
  
  getList(search="",date="") {
    var that = this;
    var params = {
      // type:that.data.datastatus,
      page: that.data.page,//当前页码1
      limit: that.data.limit,
      // p_no:that.data.p_no,
      keyword:that.data.datafind,//关键字
      // date:date,
      // search:that.data.datafind,
      // select:Number(that.data.select),

    }
    //页面功能定义 'order/get_sale_orders'|order/get_products_by_inter_id
    // request.requestGet('drawing/get_list', params, "加载中",function (res) {
    request.requestGet('order/get_sale_orders', params, "加载中",function (res) {
        console.log(res,"=====res")
      if (res.status === 200) {
        let list = that.data.projectbody
        for(let i = 0;i<res.data.data.length;i++){
          if(res.data.data[i].status === 1){
            res.data.data[i].status = "未完成"
          }else if(res.data.data[i].status != 1){
            res.data.data[i].status = "已完成"
          }
        }
        res.data.data.map((item) =>{
          return item.t = false;
        })
        if (that.data.page == 1) {
          list = []
        }
        list = [...list, ...res.data.data]
        if (list.length < res.data.count ){
          that.setData({
            page: that.data.page + 1,
            flag:true
          })
        } else {
          that.setData({
            flag:false
          })
        }
        that.setData({
          projectbody: list,
          count: res.data.count
        })
        console.log(that.data.projectbody,"AAAAAAAAAAAAAA")

      }
      }, function (res) {
        console.log(res,"请求失败")
      },
    )


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  submit(event){
  },
  bindKeyInputVant(event){
    let valueName = event.target.dataset.variable;
    let name = `formData.${valueName}`;
    this.setData({
      [valueName]:event.detail
    });
  },
  onTabChange(event){
    if(event.detail.index === 1){
      this.data.datastatus = 1
    }else if(event.detail.index === 2){
      this.data.datastatus = 0
    }else if(event.detail.index === 0){
      this.data.datastatus = 2
    }
    this.data.page = 1
    this.getList()
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
  },
  onConfirm(event) {
    this.data.page = 1
    this.setData({
      show: false,
      date: this.formatDate(event.detail[0])+' - '+this.formatDate(event.detail[1]),
      findtime : this.formatDate(event.detail[0])+' - '+this.formatDate(event.detail[1])
    });
    this.getList("",this.data.date)
  },

  onSearch(e){
    this.setData({
      flag:true
    })
    this.data.page = 1
    this.data.datafind = e.detail
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    this.getList(e.detail)
  },
  onReachBottom() {
    if(this.data.flag){
      this.setData({
        flag:false
      })
      this.getList(); // 疯狂的请求的方法
    }
  },
  comment(event){
    let tmp = event.currentTarget.dataset.index
    let pic_no = ""
    for(let i = 0;i<this.data.projectbody.length;i++){
      if(this.data.projectbody[i].id === tmp){
        pic_no = this.data.projectbody[i].pic_no
      }
    }
    wx.navigateTo({
      url: `/pages/pic_no_list_process/pic_no_list_process?p_no=${tmp}&pic_no=${pic_no}`,
    })
  },
  edit(event){
    let tmpvalue1 = this.data.projectbody[event.currentTarget.dataset.index].FCheckDate
    let tmpvalue2 = this.data.projectbody[event.currentTarget.dataset.index].FBillNo
    let tmpvalue3 = this.data.projectbody[event.currentTarget.dataset.index].FBillerID
    let tmpvalue4 = this.data.projectbody[event.currentTarget.dataset.index].CustomerName
    let tmpvalue5 = this.data.projectbody[event.currentTarget.dataset.index].department_name
    let tmpvalue6 = this.data.projectbody[event.currentTarget.dataset.index].salesman_name
    let tmpvalue7 = this.data.projectbody[event.currentTarget.dataset.index].biller_name
    let tmp ={
      // FCheckDate:this.data.projectbody[event.currentTarget.dataset.index].FCheckDate,
      // FBillNo:this.data.projectbody[event.currentTarget.dataset.index].FBillNo,
      // FBillerID:this.data.projectbody[event.currentTarget.dataset.index].FBillerID,
      // CustomerName:this.data.projectbody[event.currentTarget.dataset.index].CustomerName,
      // department_name:this.data.projectbody[event.currentTarget.dataset.index].department_name,
      // salesman_name:this.data.projectbody[event.currentTarget.dataset.index].salesman_name,
      // biller_name:this.data.projectbody[event.currentTarget.dataset.index].biller_name,
    }
    // this.data.projectbody[event.currentTarget.dataset.index]
    console.log(tmp,"====tmptmp")
    wx.navigateTo({
      url: `/pages/pic_no_list_info/pic_no_list_info?value1=${tmpvalue1}&value2=${tmpvalue2}&value3=${tmpvalue3}&value4=${tmpvalue4}&value5=${tmpvalue5}&value6=${tmpvalue6}&value7=${tmpvalue7}`,
    })
  },

  setrem(e){
    console.log(e,"eee")
    // let id = e.currentTarget.dataset.index
    // console.log(this.data.projectbody,"===========111111111")
    // console.log(id,'=======id')
    // let tmpvalue1 = this.data.projectbody[id].FInterID
    // console.log(tmpvalue1,"===tmpvalue1")
    wx.navigateTo({
      url: `/pages/pic_no_rember/pic_no_rember?FInterID=${e.currentTarget.dataset.index}&fbillno=${e.currentTarget.dataset.fbillno}`,
    })
  },
  delete(e){
    let params = {
      id:e.currentTarget.dataset.index
    }
    var that = this
    request.requestGet('drawing/del', params, "加载中",function (res) {
      if (res.status === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'success',
        })
        setTimeout(() => {
          that.onLoad({})
        }, 1000)
        } else {
          that.setData({
            flag:false
          })
        }
      }, function (res) {
        console.log(res,"请求失败")
      },
    )
  },
  need_set_pay(e){
    let id = e.currentTarget.dataset.id
    let material_no = e.currentTarget.dataset.material_no
    let num = e.currentTarget.dataset.num
    wx.navigateTo({
      url: `/pages/need_set_pay/need_set_pay?id=${id}&material_no=${material_no}&num=${num}`,
    })
  },
  del_need_pay(e){
    var that = this
    let params = {
      id:e.currentTarget.dataset.id
    }
    request.requestGet('order/removePayTicket', params, "删除中",function (res) {
      if (res.status === 200) {
        that.getList()
        } else {
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
      }, function (res) {
        console.log(res,"请求失败")
      },
    )
  },
  add_info(e){
    wx.navigateTo({
      url: `/pages/pic_no_list_info/pic_no_list_info`,
    })
  },
  look_rem(e){
    wx.navigateTo({
      url: `/pages/pic_no_material/pic_no_material`,
    })
  },


  //打印标签
  buttonClick(target) {
    let buffer = null
    console.log(target,"targettarget")
    switch (target.currentTarget.dataset.type) {
      case '文字':
        //打印标签内容是根据产品来的
        let tmp = {
          品名:'RK8152B-(1)涤纶六角网',
          订单号:'',
          缸号:'G2503082',
          颜色:'本白',
          色号:'RK8152B-(1)',
          幅宽:'1.95',
          克重:'22',
          重量:'53.4 KG',
          码数:'1302码',
          批号:'G2503082-1'
        }
        buffer = instruct.textSend(tmp)
        break
      case '产品':
        let tmp1 = {
          产品型号:'TEST12138',
          生产日期:'2025/11/2',
          产品条码:'01021600BEKJ129347',
          产品信息:'这里是产品信息,这里是产品信息,这里是产品信息,这里是产品信息',
        }
        buffer = instruct.textchanpin(tmp1)
        break
      case '条码':
        buffer = instruct.barcodeSend()
        break
      case '二维码':
        buffer = instruct.qrcodeSend()
        break
      case '样表':
        buffer = instruct.tableSend()
        break
      case "图片":
        this.chooseImage()
        break
      
    }
    if (buffer) this.writeBleChaValue(buffer)
  },

  async writeBleChaValue(bytes) {
    
    const MAX_PACKET = 20; // 每次发送的最大数据包大小
    const totalLen = bytes.length || bytes.byteLength;
    let offset = 0;
    console.log('PrintSend======', bytes.length, bytes.byteLength);
    wx.showLoading({
      title: '发送中',
    })
    while (offset < totalLen) {
      const end = Math.min(offset + MAX_PACKET, totalLen);
      const packet = bytes.slice(offset, end);
      console.log('PrintSend 发送数据:', 'offset:', offset, 'end:', end);
      // 兼容 Uint8Array/ArrayBuffer
      let dataBuffer = packet instanceof Uint8Array ? packet.buffer : packet;
      try {
        let res = await bleDisNetwork.writeBluetoothCharacteristicValue(dataBuffer);
        console.log('sendNext 发送结果:', res);
        offset = end;
      } catch (error) {
        console.error('蓝牙发送失败', error);
        return false;
      }
    }
    wx.hideLoading()
    wx.showToast({
      title: '发送成功',
      duration: 2000,
    })
    return true;
  },
})